package com.financing.wap.web.controller.api;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.ResultMap;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.FaUserWechatDTO;
import com.financing.wap.dto.FpFaUserDataDTO;
import com.financing.wap.dto.FpShopSigninDTO;
import com.financing.wap.dto.ShopperUserInfoDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IFpShopSigninService;
import com.financing.wap.service.IShopperUserInfoService;
import com.financing.wap.service.IUserService;
import com.financing.wap.service.impl.UserWechatServiceImpl;
import com.financing.wap.util.DTOdateSetUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.web.controller.BaseController;

@Controller("fpShopSigninController")
@RequestMapping("/api/fpShopSignin")
public class FpShopSigninController extends BaseController  { 

	private Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private IFpShopSigninService fpShopSigninService;
	
	@Autowired
	private IUserService iUserService;
	
	@Autowired
	private IShopperUserInfoService userInfoService; 
	
	@Autowired
	private UserWechatServiceImpl userWechatService;
	
	@Autowired
	private IUserService userService;
	
	@RequestMapping("/addFpShopSignin")
	@ResponseBody
	public ResultMap add(HttpServletRequest request,FpShopSigninDTO fpShopSignin){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("add fpShopSignin  begin .......");
			
			
			
			Session session = SessionUtil.getSession();
			String userId = session.getUser().getId();
			fpShopSignin.setId(userId);
			fpShopSignin.setSigninTime(new Date());
			
//			int id = 0;
			FpShopSigninDTO fpShopSigninDTO = fpShopSigninService.loadById(userId);
			if (fpShopSigninDTO == null) {
				fpShopSignin.setSigninNum(1);
				DTOdateSetUtil.setCreateInfo(fpShopSignin);
				DTOdateSetUtil.setUpdateInfo(fpShopSignin);
				fpShopSigninService.insert(fpShopSignin);
//				result.setAttribute("id", id);
			}else {
				if (isNow(fpShopSigninDTO.getSigninTime())) {
					result.setAttribute("msg", "您已经签到了!");
				}else {
					
					DTOdateSetUtil.setUpdateInfo(fpShopSignin);
					fpShopSignin.setSigninNum(fpShopSigninDTO.getSigninNum() + 1);
					fpShopSigninService.update(fpShopSignin);
				}
			}
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			logger.info("add fpShopSignin list end .......");
		}catch(Exception e){
			e.printStackTrace();
			log.error("add fpShopSignin error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
	
	@RequestMapping("/querySort")
	@ResponseBody
	public ResultMap querySort(HttpServletRequest request,HttpServletResponse response) {
		ResultMap result = new ResultMap();
		try {
			Session session = SessionUtil.getSession();
			String userId = session.getUser().getId();
			
			
			FpShopSigninDTO fpshopSignInInfo = fpShopSigninService.loadById(userId);
			
			Date signinTime = fpshopSignInInfo.getSigninTime();
			if (isNow(signinTime)) {
				int totalSort = fpShopSigninService.querySortByTotal(userId);
				int timeSort = fpShopSigninService.querySortByTime(userId);
				Integer signinNum = fpshopSignInInfo.getSigninNum();
				
				result.setAttribute("timeSort", timeSort);
				result.setAttribute("totalSort", totalSort);
				result.setAttribute("signinNum", signinNum);
			}else {
				result.setAttribute("msg", "您今日未签到哦!");
			}
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
		} catch (Exception e) {
			log.error("add fpShopSignin error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			e.printStackTrace();
		}
		return result;
	}
	
	
	@RequestMapping("/queryTopTen")
	@ResponseBody
	public ResultMap queryTopTen (HttpServletRequest request,HttpServletResponse response, String userPhone) throws SQLException {
		
		ResultMap resultMap = new ResultMap();
		
		try {
			
			UserDTO ud = new UserDTO();
			ud.setLoginName(userPhone);
			UserDTO user = userService.queryUserLoginName(ud);
		
			List<FpShopSigninDTO> queryTopTens = fpShopSigninService.queryTopTen();
			
			if (queryTopTens != null && queryTopTens.size() != 0) {
				for (FpShopSigninDTO fpShopSigninDTO : queryTopTens) {
					String userId_top = fpShopSigninDTO.getId();
					ShopperUserInfoDTO shopperUserInfo = new ShopperUserInfoDTO();
					shopperUserInfo.setUserId(userId_top);
					List<ShopperUserInfoDTO> queryshopperUserInfo =  userInfoService.queryList(shopperUserInfo);
					String headImgurl = null;
					if (queryshopperUserInfo != null && queryshopperUserInfo.size() != 0) {
						if (StringUtil.isNullOrEmptyStr(queryshopperUserInfo.get(0).getUserHeadImg())) {
							FaUserWechatDTO faUserWechatDTO = new FaUserWechatDTO();
							faUserWechatDTO.setUserId(userId_top);
							FaUserWechatDTO faUserWechat = userWechatService.queryUserWechatInfo(faUserWechatDTO);
							if (faUserWechat != null) {
								if (!StringUtil.isNullOrEmptyStr(faUserWechat.getHeadimgurl())) {
									headImgurl = faUserWechat.getHeadimgurl();	
								}
							}
						}else {
							headImgurl = queryshopperUserInfo.get(0).getUserHeadImg();
						}
					}
					
					fpShopSigninDTO.setFaImage(headImgurl);
				}
			}
			
			
			
			FpShopSigninDTO fpUser = fpShopSigninService.loadById(user.getId());
			if (fpUser != null) {
				Date currentDate = new Date();
				Date signinTime = fpUser.getSigninTime();
				Calendar cal1 = Calendar.getInstance();
				cal1.setTime(currentDate);
				// 将时分秒,毫秒域清零
				cal1.set(Calendar.HOUR_OF_DAY, 0);
				cal1.set(Calendar.MINUTE, 0);
				cal1.set(Calendar.SECOND, 0);
				cal1.set(Calendar.MILLISECOND, 0);
				Date formatCurrentTime = cal1.getTime();
				
//				Calendar cal2 = Calendar.getInstance();
				cal1.setTime(signinTime);
				// 将时分秒,毫秒域清零
				cal1.set(Calendar.HOUR_OF_DAY, 0);
				cal1.set(Calendar.MINUTE, 0);
				cal1.set(Calendar.SECOND, 0);
				cal1.set(Calendar.MILLISECOND, 0);
				Date formtSigninTime = cal1.getTime();
				
//				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//				Date formatCurrentTime =sdf.parse(sdf.format(currentDate)) ;
//				Date formtSigninTime = sdf.parse(sdf.format(signinTime));
				 if (formtSigninTime.before(formatCurrentTime)) {
					 resultMap.setAttribute("signIn", false);//未签到
				}else {
					resultMap.setAttribute("signIn", true);//已签到
				}
			}else {
				resultMap.setAttribute("signIn", false);//未签到
			}
			
			resultMap.setAttribute("topTens", queryTopTens);
			resultMap.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			resultMap.setStatus(ResultMap.STATUS.SUCCESS);
		} catch (Exception e) {
			log.error("add fpShopSignin error!",e);
			resultMap.setStatus(ResultMap.STATUS.ERROR);
			resultMap.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			e.printStackTrace();
		}
		return resultMap;
	}

	/**
     * 判断时间是不是今天
     * @param date
     * @return    是返回true，不是返回false
     */
    private static boolean isNow(Date date) {
        //当前时间
        Date now = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
        //获取今天的日期
        String nowDay = sf.format(now);
        //对比的时间
        String day = sf.format(date);
         
        return day.equals(nowDay);
         
         
         
    }
	
	
}